<?php

namespace backend\controllers;

use backend\models\UploadForm;
use common\models\ProjectLog;
use common\models\ProjectUpdateLog;
use common\models\UploadImgForm;
use PhpOffice\PhpWord\Shared\ZipArchive;
use Yii;
use common\models\Responses;
use common\models\ProjectInvestigationFile;
use common\models\ProjectInvestigationFileSearch;
use yii\data\Pagination;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
use yii\widgets\LinkPager;

/**
 * 尽调报告——关键附件
 */
class ProjectInvestigationFileController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return parent::behaviors();
    }


    /**
     * 上传图片
     * @return array
     */
    public function actionUpload()
    {
        if (Yii::$app->request->isPost) {
            $userId = Yii::$app->user->id;
            //$project_id = (int)Yii::$app->request->post('project_id');
            //$category = Yii::$app->request->post('category', 0);
            $project_id = (int)Yii::$app->request->get('project_id');
            $category = Yii::$app->request->get('category', 0);

            if ($project_id <= 0) {
                return Responses::response400('没有传输项目id', true);
            }

            $projectInvestigationFile = new ProjectInvestigationFile();
            $model = new UploadImgForm();
            $model->imageFiles = UploadedFile::getInstances($model, 'imageFiles');
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

            $re = $model->upload();
            if ($re['state']) {
                if (!empty($re['data']) && is_array($re['data'])) {
                    $result = $projectInvestigationFile->adds($userId, $project_id, $category, $re['data']);
                    if ($result['state']) {

                        /***********************  列表及分页 start  *******************/
                        $page = 1;//当前页
                        $pageSize = 10;//每页条数
                        $category = 0;
                        $state = 0;  //1是，2否，默认全部
                        if ($project_id > 0) {
                            //查询条件
                            $where = ['project_id' => $project_id];
                            if ($state > 0) {
                                $where['state'] = $state;
                            }
                            if ($category > 0) {
                                $where['category'] = $category;
                            }

                            //列表数据
                            $projectInvestigationFile = new ProjectInvestigationFile();
                            $count = $projectInvestigationFile->getCounts($where);
                            $totalPage = ceil($count / $pageSize);
                            //重设当前页
                            if ($page < 1) {
                                $page = 1;
                            } elseif ($page > $totalPage) {
                                $page = $totalPage;
                            }
                            $offset = ((int)$page - 1) * $pageSize;
                            $list = $projectInvestigationFile->getList($where, $limit = $pageSize, $offset);

                            //--------------分页数据--------------
                            $query = ProjectInvestigationFile::find()->where($where);
                            $countQuery = clone $query;
                            $count = $countQuery->count();
                            $pages = new Pagination(['pageSize' => $pageSize, 'totalCount' => $count]);
                            $linkpager = LinkPager::widget([
                                'pagination' => $pages,
                                'hideOnSinglePage' => false,
                                'maxButtonCount' => 10, //默认显示10页
                                'nextPageLabel' => '下一页',
                                'prevPageLabel' => '上一页',
                                'firstPageLabel' => '首页',
                                'lastPageLabel' => '尾页',
                                //'options' => ['class' => 'm-pagination'],
                            ]);
                        }
                        $data = array('list' => $list, 'pager' => $linkpager, 'count' => $count, 'page' => $page);
                        /***********************  列表及分页 end  *******************/

                        return Responses::response200($data, 1, $result['msg']);
                    } else {
                        return Responses::responseError($result['data'], $result['msg'], true);
                    }
                }
            } else {
                return Responses::response400($re['msg'], true);
            }
        }
    }

    /**
     * 上传附件删除图片
     */
    public function actionDeleteFile()
    {
        if (Yii::$app->request->isPost) {
            $userId = Yii::$app->user->id;
            $project_id = (int)Yii::$app->request->post('project_id');
            $fileName = Yii::$app->request->post('file_name');
            $type = Yii::$app->request->post('type');

            $model = ProjectInvestigationFile::find()->where(['project_id' => $project_id, 'file_name' => $fileName, 'uploaded_by' => $userId])->one();

            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

            //删除上传失败文件
            if ($type == 2) {
                $webroot = Yii::getAlias('@webroot');
                $path = UploadImgForm::PATH;
                $file = $webroot . '/' . $path . $fileName;
                if (is_file($file)) {
                    unlink($file);
                } else {
                    return Responses::response400("{$fileName}该图片下存在", true);
                }
            } else {
                $transaction = Yii::$app->db->beginTransaction();
                try {
                    if (!empty($model)) {
                        $fileName = $model->file_name;
                        $olderFileName = $model->title;

                        $res = (new ProjectInvestigationFile())->setUpdateLog($model->id, $project_id, array(), $userId, ProjectUpdateLog::MODULE_FILE, 3);
                        if (!$res['state']) {
                            throw new \Exception($res['msg']);
                        }

                        if ($model->delete()) {
                            $webroot = Yii::getAlias('@webroot');
                            $path = UploadImgForm::PATH;
                            $file = $webroot . '/' . $path . $fileName;
                            if (is_file($file)) {
                                unlink($file);
                            } else {
                                throw new \Exception("{$olderFileName}该图片下存在");
                            }
                        } else {
                            throw new \Exception('删除失败');
                        }
                    } else {
                        throw new \Exception('删除失败');
                    }

                    $transaction->commit();
                    return Responses::response200(array(), 1, '删除成功');
                } catch (\Exception $e) {
                    $transaction->rollBack();
                    $message = $e->getMessage();
                    return Responses::response400($message, true);
                } catch (\Throwable $e) {
                    $transaction->rollBack();
                    $message = $e->getMessage();
                    return Responses::response400($message, true);
                }
            }
            return Responses::response200(array(), 1, '删除成功');
        }
    }

    /**
     * 分页列表
     * @return array
     */
    public function actionAjaxList()
    {
        if (Yii::$app->request->isAjax) {
            $page = (int)Yii::$app->request->get('page', 1);//当前页
            $pageSize = (int)Yii::$app->request->get('pageSize', 10);//每页条数
            $category = (int)Yii::$app->request->get('category', 0);
            $state = (int)Yii::$app->request->get('state', 0);  //1是，2否，默认全部
            $projectId = (int)Yii::$app->request->get('project_id');

            if ($projectId > 0) {
                //查询条件
                $where = ['project_id' => $projectId];
                if ($state > 0) {
                    $where['state'] = $state;
                }
                if ($category > 0) {
                    $where['category'] = $category;
                }

                //列表数据
                $projectInvestigationFile = new ProjectInvestigationFile();
                $count = $projectInvestigationFile->getCounts($where);
                $totalPage = ceil($count / $pageSize);
                //重设当前页
                if ($page < 1) {
                    $page = 1;
                } elseif ($page > $totalPage) {
                    $page = $totalPage;
                }
                $offset = ((int)$page - 1) * $pageSize;
                $list = $projectInvestigationFile->getList($where, $limit = $pageSize, $offset);

                //--------------分页数据--------------
                $query = ProjectInvestigationFile::find()
                    ->where($where);

                $countQuery = clone $query;
                $count = $countQuery->count();
                $pages = new Pagination(['pageSize' => $pageSize, 'totalCount' => $count]);
                $linkpager = LinkPager::widget([
                    'pagination' => $pages,
                    'hideOnSinglePage' => false,
                    'maxButtonCount' => 10, //默认显示10页
                    'nextPageLabel' => '下一页',
                    'prevPageLabel' => '上一页',
                    'firstPageLabel' => '首页',
                    'lastPageLabel' => '尾页',
                    //'options' => ['class' => 'm-pagination'],
                ]);

                Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                return Responses::response200(array('list' => $list, 'pager' => $linkpager, 'count' => $count, 'page' => $page), 'success', true);
            }
        }
    }

    /**
     * 删除数据
     */
    public function actionDelete()
    {
        if (Yii::$app->request->isAjax) {
            $userId = (int)Yii::$app->user->id;
            $id = (int)Yii::$app->request->post('id');
            $projectId = (int)Yii::$app->request->post('project_id');
            $model = ProjectInvestigationFile::find()->where(['project_id' => $projectId, 'id' => $id])->one();
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

            $transaction = Yii::$app->db->beginTransaction();
            try {
                if ($model === null) {
                    throw new \Exception('该数据不存在');
                }

                $res = (new ProjectInvestigationFile())->setUpdateLog($id, $projectId, array(), $userId, ProjectUpdateLog::MODULE_FILE, 3);
                if (!$res['state']) {
                    throw new \Exception($res['msg']);
                }

                if ($model->delete()) {
                    $webroot = Yii::getAlias('@webroot');
                    $file = $webroot . '/' . UploadImgForm::PATH . $model->file_name;
                    if (file_exists($file)) {
                        $res = unlink($file);
                        if (!$res) {
                            return Responses::response400('删除失败', 1);
                        }
                    }
                } else {
                    return Responses::response400('删除失败', 1);
                }

                $transaction->commit();
                return Responses::response200(array(), 1, '删除成功');
            } catch (\Exception $e) {
                $transaction->rollBack();
                $message = $e->getMessage();
                return Responses::response400($message, true);
            } catch (\Throwable $e) {
                $transaction->rollBack();
                $message = $e->getMessage();
                return Responses::response400($message, true);
            }
        }
    }

    /**
     * 编辑
     * @return array
     */
    public function actionEdit()
    {
        if (Yii::$app->request->isAjax) {
            $userId = (int)Yii::$app->user->id;
            $id = (int)Yii::$app->request->post('id');
            $projectId = (int)Yii::$app->request->post('project_id');
            $state = (int)Yii::$app->request->post('state');
            $category = (int)Yii::$app->request->post('category');
            $title = Yii::$app->request->post('title');
            $model = ProjectInvestigationFile::find()->where(['project_id' => $projectId, 'id' => $id])->one();

            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

            $transaction = Yii::$app->db->beginTransaction();
            try {
                $changedAttributes = array();
                if (!empty($model)) {
                    if ($state > 0) {
                        $model->state = $state;
                        $changedAttributes['state'] = $state;
                    }
                    if ($category > 0) {
                        $model->category = $category;
                        $changedAttributes['category'] = $category;
                    }
                    if ($title != '') {
                        $model->title = $title;
                        $changedAttributes['title'] = $title;
                    }

                    $res = $model->setUpdateLog($id, $projectId, $changedAttributes, $userId, ProjectUpdateLog::MODULE_FILE, 2);
                    if (!$res['state']) {
                        throw new \Exception($res['msg']);
                    }

                    if ($model->save()) {
                        $transaction->commit();
                        return Responses::response200(array(), 1, '修改成功');
                    } else {
                        $error = $model->getFirstErrors();
                        $message = '';
                        if (!empty($error)) {
                            foreach ($error as $value) {
                                $message .= $value;
                            }
                            $tmpStr = strip_tags($message);
                            $tmpLen = mb_strlen($tmpStr);
                            $message = mb_substr($tmpStr, 0, $tmpLen, 'utf-8');
                        }
                        throw new \Exception($message);
                    }
                }
                throw new \Exception('修改失败');

            } catch (\Exception $e) {
                $transaction->rollBack();
                $message = $e->getMessage();
                return Responses::response400($message, true);
            } catch (\Throwable $e) {
                $transaction->rollBack();
                $message = $e->getMessage();
                return Responses::response400($message, true);
            }
        }
    }

    /**
     * 下载图片
     */
    public function actionDownload()
    {
        $userId = (int)Yii::$app->user->id;
        $id = (int)Yii::$app->request->get('id');
        $projectId = (int)Yii::$app->request->get('project_id');
        $model = ProjectInvestigationFile::find()->where(['project_id' => $projectId, 'id' => $id])->one();
        if (!empty($model)) {
            $webroot = Yii::getAlias('@webroot');
            $file = $webroot . '/' . UploadImgForm::PATH . $model->file_name;
            if (file_exists($file)) {
                $model->download_count = $model->download_count + 1;
                $model->save();

                $projectLogModel = new ProjectLog();
                $projectLogModel->project_id = $projectId;
                $projectLogModel->created_at = date('Y-m-d H:i:s', time());
                $projectLogModel->user_id = $userId;
                $projectLogModel->log = "下载图片【{$model->title}】";
                $projectLogModel->save();

                Yii::$app->response->sendFile($file, $model->title)->send();
            }
        }
    }

    /**
     * 批量下载
     *     删除之前zip文件
     *     创建zip文件，把每个文件放入其中并下载（同我文件只显示一个）
     *     操作记录
     */
    public function actionDownloadZip()
    {
        $userId = (int)Yii::$app->user->id;
        $ids = Yii::$app->request->get('ids');
        $orders = Yii::$app->request->get('orders');
        $projectId = (int)Yii::$app->request->get('project_id');
        if ($ids != '') {
            $webroot = Yii::getAlias('@webroot');
            $path = $webroot . '/' . UploadImgForm::PATH;
            //遍历删除之前压缩包
            if($handle = opendir($path)){
                while (false !== ($file = readdir($handle))){
                    if (substr($file,strrpos($file,'.')+1) == 'zip') {
                        unlink($path .$file);
                    }
                }
                closedir($handle);
            }

            $ids = explode(',', $ids);
            $orders = explode(',',$orders);
            $list = ProjectInvestigationFile::find()->where(['project_id' => $projectId])->andWhere(['in', 'id', $ids])->orderBy(['state' => SORT_ASC, 'id' => SORT_DESC])->All();
            if (!empty($list)) {
                $log = array();

                //压缩文件
                $zip = new ZipArchive();
                $fileZip = $path . date("YmdHis") . '_' . rand(10000, 99999) . '.zip';
                $zip->open($fileZip, ZipArchive::CREATE);
                foreach ($list as $key => $model) {
                    $log[] = $model->title;
                    $file = $path . $model->file_name;
                    if (file_exists($file)) {
                        $newName = iconv("UTF-8","gb2312",$model->title);
                        $zip->addFile($file, ($orders[$key]) . '-' . $newName);   //向压缩包中添加文件
                    }

                    //下载次数加一
                    $model->download_count = $model->download_count + 1;
                    $model->save();
                }
                $zip->close();
                if (!file_exists($fileZip)) {
                    exit("无法找到文件"); //即使创建，仍有可能失败。。。
                }

                //批量下载记录
                $projectLogModel = new ProjectLog();
                $projectLogModel->project_id = $projectId;
                $projectLogModel->created_at = date('Y-m-d H:i:s', time());
                $projectLogModel->user_id = $userId;
                //$projectLogModel->log = "批量下载：". join(',', $log);
                $projectLogModel->log = "批量下载";
                $projectLogModel->save();

                Yii::$app->response->sendFile($fileZip)->send();
            }
        }
    }


    /**
     * Lists all ProjectInvestigationFile models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new ProjectInvestigationFileSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single ProjectInvestigationFile model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new ProjectInvestigationFile model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new ProjectInvestigationFile();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing ProjectInvestigationFile model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing ProjectInvestigationFile model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
//    public function actionDelete($id)
//    {
//        $this->findModel($id)->delete();
//
//        return $this->redirect(['index']);
//    }

    /**
     * Finds the ProjectInvestigationFile model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return ProjectInvestigationFile the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = ProjectInvestigationFile::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
